/**
 * @author wanghua
 * @date 2021/10/02
 */

 import axios from 'axios'
 import router from '@/router';
 import sysConfig from "@/config";
 import { ElMessageBox, ElMessage } from 'element-plus'
 import {AuthToken} from '@/utils/token-util'
 import qs from 'qs'
 
 axios.defaults.timeout = 30000;
 
 let myaxios = axios.create({
   baseURL: import.meta.env.PROD ? '/' : import.meta.env.VITE_APP_BASE_API,
   timeout: 30000,
   headers:{'Content-Type': 'application/x-www-form-urlencoded'}
  });
 
  // request interceptor
  myaxios.interceptors.request.use(
   config => {
     let token = AuthToken.getToken();
     if(token){
       let headers = config.headers as Record<string, string>;
       headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
     }
     if(!sysConfig.REQUEST_CACHE && config.method == 'get'){
       config.params = config.params || {};
       config.params['_'] = new Date().getTime();
     }
     Object.assign(config.headers, sysConfig.HEADERS)
     return config;
   },
   error => {
     return Promise.reject(error)
   },
 )
 
 // response interceptor
 myaxios.interceptors.response.use(
   response => {
     return response;
   },
   error => {
     debugger;
     if (error.response) {
       if (error.response.status == 404) {
         ElMessage.error("Status:404，正在请求不存在的服务接口！");
       } else if (error.response.status == 500) {
         ElMessage.error("Status:500，服务器发生错误！");
       } else if (error.response.status == 401) {
         ElMessageBox.confirm('当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作', '无权限访问', {
           type:"error",
           confirmButtonText: '重新登录',
           cancelButtonText: '取消',
           callback: (action:any) => {
             return new Promise((resolve, reject) => {
               router.replace({path: '/login'});
             }).catch(() => console.log('Oops errors!'));
           },
         });
       } else {
         let msg = error.response.data.errMsg || error.response.data.errorMessage || `Status:${error.response.status}，未知错误！`;
         ElMessageBox.alert(msg, '出错了...', { type:"error" });
       }
     } else {
       ElMessage.error("请求服务器无响应！");
     }
 
     return Promise.reject(error.response);
   },
 )
 
 if (import.meta.env.PROD) {
   
 }
 
 const myhttp = new class{
   
   urlprix = 'api/';
 
   checkAndShowResponseError(responseData: any){
     if(!responseData)return true;
     if(responseData.hasError){
       let errMsg = responseData.errMessage || responseData.errorMessage;      
       console.log(errMsg);
       ElMessageBox.alert(errMsg, '出错了...', { type:"error" });      
       return false;
     }
     return true;
   }
 
   buildConfig(headers:{}, config={}){
     let axiosHeaders : any = headers;
     if(!axiosHeaders) axiosHeaders = {};
     axiosHeaders[AuthToken.RequestHeaderName] = AuthToken.getToken();
     axiosHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
 
     let axiosConfig : any = config;
     if(!axiosConfig) axiosConfig = {};
     axiosConfig.headers = headers;
     return axiosConfig;
   }
 
   get(url:string, useDefaultErrorHandler:boolean=true, headers:any={}, config:any={}){
     let axiosConfig : any = this.buildConfig(headers, config);
 
     //不使用浏览器缓存（避免表单数据修改后，再次获取数据时不更新）
     if(url.indexOf('?')>=0){
       url=url+"&"+(new Date()).getTime();
     }else{
       url=url+"?"+(new Date()).getTime();
     }
 
     return new Promise((resolve, reject) => {
       try{
         myaxios.get(url, axiosConfig).then((response) => {
           if(useDefaultErrorHandler){//使用默认的错误处理
             let resData :any = response.data;
             if(!this.checkAndShowResponseError(resData)){
               reject(new ResponseError("err-handler","", response));
             }else{
               resolve(response); 
             }
           }else{         
             resolve(response);          
           }
         }).catch((error) => {
           console.error(error);
           reject(new ResponseError("err-http","", error));
         })
       }catch(error){
         console.error(error);
         reject(new ResponseError("err-socket","", error));
       }
     })
   }
 
   post(url:string, data:any={}, useDefaultErrorHandler:boolean=true, headers:any={}, config:any={}){
     let axiosConfig : any = this.buildConfig(headers, config);
     let formData = qs.stringify(data);
     return new Promise((resolve, reject) => {
       try{
         myaxios.post(url, formData, axiosConfig).then((response) => {
           if(useDefaultErrorHandler){//使用默认的错误处理
             let resData :any = response.data;
             if(!this.checkAndShowResponseError(resData)){
               reject(new ResponseError("err-handler","", response));
             }else{
               resolve(response); 
             }
           }else{         
             resolve(response);          
           }
         }).catch((error) => {
           console.error(error);
           reject(new ResponseError("err-http","", error));
         })
       }catch(error){
         console.error(error);
         reject(new ResponseError("err-socket","", error));
       }
     })
   }
 }
 
 class ResponseError{
   type:string;
   code:string;
   error:any;
   constructor(type:string, code:string, error:any){
     this.type = type;
     this.code = code;
     this.error = error;
   }
 }
 //外部请求可以使用myaxios，内部请求一般使用myhttp
 export {myaxios, myhttp, ResponseError};
 